package cn.manter.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("333333");
        // 1.从请求头中获取token，判断是否存在
        String token = request.getHeader("token");
        // 1.1.不存在，返回一个{"success":false,"message":"noLogin"},再返回false
        if (token != null){
            Object logininfo = redisTemplate.opsForValue().get(token);
            if (logininfo != null){
                // 3.刷新token过期时间
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                // 4.放行
                return true;
            }
        }
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;

    }
}
